package com.su.sweet.socket;

import org.smartboot.socket.Protocol;
import org.smartboot.socket.transport.AioSession;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class DecoderProtocolImpl implements Protocol<String> {

    @Override
    public String decode(ByteBuffer byteBuffer, AioSession aioSession) {
        byteBuffer.order(ByteOrder.BIG_ENDIAN);
        int remaining = byteBuffer.remaining();
        if (remaining < Integer.BYTES) {
            return null;
        }
        byteBuffer.mark();
        int length = byteBuffer.getInt();
        if (length > byteBuffer.remaining()) {
            byteBuffer.reset();
            return null;
        }
        byte[] b = new byte[length];
        byteBuffer.get(b);
        byteBuffer.mark();
        return new String(b);
    }
}
